﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lm.Common.ExtensionMethods;

namespace Lm.Common.Auth.Account
{
    [Operation.Operation("{18AFB218-B6D1-42B7-A3D0-E194DD7E54A2}", "修改自己的密码", "")]
    public class ChangePassword : Operation.OperationBase
    {
        static ChangePassword()
        { Operation.OperationBase.CreateOperation(typeof(ChangePassword)); }
        
        public ChangePassword(string token)
            : base(token)
        { }

        public void Change(string oldPassword, string newPassword1, string newPassword2)
        {
            if (this.Token.OperatorAccount != this.Token.OwnerAccount)
            { throw new Exception("使用他人授权登录时，不能修改密码"); }
            if (oldPassword.IsNullOrBlank())
            { throw new Exception("旧密码不能为空"); }
            if (newPassword1.IsNullOrBlank() || newPassword2.IsNullOrBlank())
            { throw new Exception("新密码不能为空"); }            
            if (newPassword1 != newPassword2)
            { throw new Exception("两次输入的密码不一致"); }
            if (newPassword1 == oldPassword)
            { throw new Exception("新旧密码相同，无需修改"); }
            string newPassword = new Lm.Common.Security.Cryptography.Md5Computer().Compute(newPassword1);
            oldPassword = new Lm.Common.Security.Cryptography.Md5Computer().Compute(oldPassword);
            using (var tran = new System.Transactions.TransactionScope())
            {
                var account = new AccountDal().GetByUserId(this.Token.OwnerAccount);
                if (account.Password != oldPassword)
                { throw new Exception("旧密码错误"); }

                var helper = DAL.DALFactory.Create();                
                if (helper.Update<Model.Account>(t => new Model.Account() { Password = newPassword }, t => t.Id == this.Token.OwnerAccount) != 1)
                { throw new Exception("修改密码失败"); }
                tran.Complete();
            }
        }
    }
}
